import json
import requests
import re


# 检查是否为需要解析的bilibili链接或BV号
def check(url):
    pattern = re.compile(
        r'(https:\/\/(www|m)\.bilibili\.com\/video\/)?BV(\w){10}')
    if pattern.match(url) == None:
        return False
    return True


def analysis(url):
    # 正则匹配bvid
    pattern = re.compile(r'(BV(.){10})')
    bvid = pattern.findall(url)[0][0]

    # 通过B站API用bvid获取cid
    response = requests.get(
        url='https://api.bilibili.com/x/player/pagelist?bvid=' + bvid)
    result = json.loads(response.text)
    cid = str(result['data'][0]['cid'])
    # print(cid)

    # 通过B站API用bvid和cid获取avid
    response = requests.get(
        url='https://api.bilibili.com/x/web-interface/view?cid=' + cid + '&bvid=' + bvid)
    result = json.loads(response.text)
    avid = str(result['data']['aid'])
    # print(avid)

    # 通过B站API用avid和cid获取视频链接
    response = requests.get(
        url='https://api.bilibili.com/x/player/playurl?avid=' + avid + '&cid=' + cid + '&qn=1&type=&otype=json&platform=html5&high_quality=1')
    result = json.loads(response.text)
    videoUrl = result['data']['durl'][0]['url'].replace('\\u0026', '&')
    # print(videoUrl)

    return videoUrl


if __name__ == '__main__':
    print(check('https://www.bilibili.com/video/BV1RF411B7hT?spm_id_from=333.934.0.0'))
    print(check('https://www.bilibili.com/video/BV1RF411B7h?spm_id_from=333.934.0.0'))
    print(check('BV1RF411B7hT'))
    print(check('BV1RF411B7h'))
    print(check('https://m.bilibili.com/video/BV1db4y1i7jT'))
    analysis('https://www.bilibili.com/video/BV1RF411B7hT?spm_id_from=333.934.0.0')
